'''
Created on 2009-10-30

@author: yuchen
'''
#Note at 11.3: 1.Change function name "*Position" into "*BoardPosition"

import gamemodel.player
import gamemodel.piece


class CheckerBoard(object):

	def __init__(self):
		self.girds = []
	
	@staticmethod
	def constructEmptyBoard():
		instance = CheckerBoard()
		return instance
	
	@staticmethod
	def constructWithPlayer(player0, player1):
		instance = CheckerBoard.constructEmptyBoard()
		instance.setPlayer0(player0)
		instance.setPlayer1(player1)
		return instance

	def getPlayer0(self):
		return self.player0
	
	def getPlayer1(self):
		return self.player1
	
	def setPlayer0(self, player):
		self.player0 = player
	
	def setPlayer1(self, player):
		self.player1 = player
	
	def getPlayers(self):
		return [self.player0, self.player1]
	
	def getBoardPosition(self, x, y, player):
		if player == self.player0:
			return self.girds[x][y]
		else:
			return  self.girds[9-x][9-y]
	
	def convertCoords(self, coords, player):
		if player == self.player0:
			return coords
		else:
			return  (9 - coords[0], 9 - coords[1])

	def setBoardPosition(self, x, y, player, piece):
		
		if player == self.player0:
			self.girds[x][y] = piece
		else :
			try:
				self.girds[9-x][9-y] = piece
			except Exception as e:
				pass

	def deleteBoardPosition(self, x, y, player):
		self.setBoardPosition(x, y, player, None)

	def isEmpty(self, x, y, player):
		return self.getBoardPosition(x, y, player) == None 

	def deletePiece(self, x, y, player):
		# it will throw error 'No object ....' if no piece is in this position 
		piece = self.getBoardPosition(x, y, player)
		if piece != None :
			piece.eaten()
			self.deleteBoardPosition(x, y, player)
			
	def reset(self):
		self.clear()
		for i in range(10):
			for j in range(4):
				if i % 2 == j % 2:
					self.addPiece(self.player0, i, j)
					self.addPiece(self.player1, i, j)
					
	def clear(self):
		self.girds = [([None] * 10) for i in range(10)]
		self.player0.reset();
		self.player1.reset();
	
	def addPiece(self, player, i, j, bKing = False):
		piece = gamemodel.piece.CheckerPiece(player, i, j)
		self.setBoardPosition(i, j, player, piece)
		player.add_piece(piece)
		
		if bKing:
			piece.turn_king()
		
	